package com.vagavaga.bizworld;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;


class DefaultSessionProducer implements SessionProducer {
    private static final Logger log = Logger.getLogger(DefaultSessionProducer.class);
    private final String name;

    public DefaultSessionProducer(String name) {
        if (name == null) throw new IllegalArgumentException("Persistent Unit Name must be set");
        this.name = name;
    }

    public Map<Object, Object> getConfiguration() {
        Properties props = new Properties();
        File file = new File(name + ".properties"); //$NON-NLS-1$
        try {
            BufferedInputStream is = new BufferedInputStream(new FileInputStream(file));
            try {
                props.load(is);
            } catch (IOException e) {
                String text = String.format("Error while loading properties from <%s>.", file.getAbsolutePath());

                log.fatal(text, e);
                throw new RuntimeException(text, e);
            } finally {
                is.close();
            }
        } catch (IOException e) {
            String text = String.format(
                    "Configuration file named <%s> could not be used because of an error!",
                    file.getAbsolutePath());
            log.warn(text, e);
        }
        return props;
    }

    public String getPersistenceUnitName() {
        return name;
    }

    @Override
    public int hashCode() {
        int r = 17;
        r = 37 * r + name == null ? 0 : name.hashCode();
        return r;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) return true;

        if (!(obj instanceof DefaultSessionProducer)) return false;

        DefaultSessionProducer that = (DefaultSessionProducer) obj;

        return this.name == null ? that.name == null : this.name.equals(that.name);
    }
}
